<?php
declare (strict_types=1);

namespace app\exam\model\admin;

use app\common\model\BaseModel;
use app\exam\model\Paper;
use app\user\model\user\admin\Account;

/**
 * 定义派发考试数据模型
 */
class PaperStudent extends BaseModel
{
    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'exam_paper_student';

    /**
     * 设置自动写入时间
     *
     * @var boolean
     */
    protected $autoWriteTimestamp = true;

    /**
     * 时间显示格式
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i';

    /**
     * 定义表主键
     *
     * @var string
     */
    protected $pk = 'id';

    protected $type = [
        'exam_stime' => 'timestamp',
        'exam_etime' => 'timestamp',
    ];

    /**
     * 全局查询范围
     *
     * @var [type]
     */
    protected $globalScope = ['mhm'];

    /**
     * 限制机构条件
     *
     * @param $query
     */
    public function scopeMhm($query)
    {
        $query->where('mhm_id', request()->mhm_id);
    }

    /**
     * 新增事件
     *
     * @static
     * @param \think\Model $agreement
     * @return mixed|void
     */
    public static function onBeforeInsert($agreement)
    {
        // 机构
        $agreement->mhm_id = $agreement->getAttr('mhm_id') ?: request()->mhm_id;
    }

    /**
     * 关联用户
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-30
     *
     * @return   [type]                         [description]
     */
    public function user()
    {
        return $this
            ->belongsTo(Account::class, 'user_id')
            ->with(['avatar_url'])
            ->removeOption('soft_delete')
            ->removeWhereField('mhm_id');
    }

    /**
     * 关联试卷
     */
    public function paper()
    {
        return $this->belongsTo(Paper::class, 'paper_id');
    }
}
